package com.example.cheapshark.mobile;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;

public class CSLoadingActivity extends Activity {
	private int counter = CSMobileApplication.getNumberOfPages();

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_loading);

		for (int i = 0; i < CSMobileApplication.getNumberOfPages(); i++) {
			new LoadTask(this, i).execute();

		}
		Intent goToLists = new Intent(this, TopDealsPagerActivity.class);
		this.startActivity(goToLists);

	}

	public synchronized void UpdateLoadCounter() {
		if (counter > 0) {
			counter--;
		}
	}

	public synchronized void FinishLoading() {
		counter = -1;
		Intent goToLists = new Intent(this, TopDealsPagerActivity.class);
		this.startActivity(goToLists);
	}

	public int getCounter() {
		return this.counter;
	}

	public class LoadTask extends AsyncTask<Void, Void, Void> {
		private int storeIndex;
		private CSMobileApplication state;

		public LoadTask(Context context, int count) {
			storeIndex = count;
		}

		protected Void doInBackground(Void... voids) {
			state = (CSMobileApplication) getApplicationContext();
			String query = GameDealQueries.getTopDeals(storeIndex);
			String response;
			try {
				response = HTTPRequester.StringRequest(query);
				JSONArray json = new JSONArray(response);
				GameDeal[] output = GameDeal.ConstructArray(json);
				state.setDeals(storeIndex, output);
				// Log.e("CSLoading Activity", "Completed store: " +
				// storeIndex);
				// for (int x = 0; x < json.length(); x++)
				// Log.e("CSLoading Activity", " output-json:/n" + json.get(x));
				//
				// for (int x = 0; x < output.length; x++)
				// Log.e("CSLoading Activity", " output-output:/n" +
				// output[x].getTitle());
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;
		}

		protected void onPostExecute(Void data) {
			UpdateLoadCounter();
			state.setStoreReady(storeIndex);
		}
	}
}
